# -*- coding: utf-8 -*-

from PyQt5 import uic
from PyQt5 import QtWidgets
import numpy as np
import json
from PyQt5.QtCore import QSettings, QPoint, QSize
from PyQt5.QtWidgets import QApplication

import pyqtgraph as pg
import os

# qt_creator_file = "curvesform.ui"


qt_creator_file = os.path.join(os.path.dirname(__file__),"ui_config", "curvesform.ui")
Ui_MainWindow, QtBaseClass = uic.loadUiType(qt_creator_file)

ini_file = os.path.join(os.path.dirname(__file__), "ui_config","curveFormSetting.ini")

config_file = os.path.join(os.path.dirname(__file__),"ui_config", 'user_config_curve_form.json')

Ui_MainWindow, QtBaseClass = uic.loadUiType(qt_creator_file)
import debugPrinter as dp

class CurvesForm(QtWidgets.QWidget, Ui_MainWindow):

    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.setWindowTitle("Signals")

        self.pw = pg.plot(title="sig")
        self.plt = self.pw.getPlotItem()

        curves_eeg_num = 32
        # curves_eeg_num = 24

        self.curves_num_constant = curves_eeg_num

        # channel names use this strings
        # corresponding curves use number as index, because the data array come as matrix, we use number index to get every channel
        self.ch_list = ['TP9','C4','C3','F4',   'F3','Fp2','Fp1','Fz',
                        'TP10','Cz','Pz','P3',  'P4','O1','O2','Oz',
                        'AF3','AF4','F7','F8','FC5','FC1','FC2','FC6',
                        'P8','P7','CP2','CP1',  'CP6','CP5','T8','T7']

        self.checkboxes = {}
        for name in self.ch_list:
            checkbox_name = f"checkBox_{name}"  # 动态创建名字
            self.checkboxes[name] = getattr(self, checkbox_name)  # 将控件对象存入字典

        self.curves=[]
        for ch_name in self.ch_list:
            c = self.pw.plot()
            # cc = {ch_name,c}
            self.curves.append(c) 

        # for i in range(self.curves_num_constant):
        #     c = self.pw.plot()
        #     self.curves.append(c) 

        self.scale_offset = 200

        self.gridLayout.addWidget(self.pw)
        self.pw.setLabel('bottom', 'Time', 's')
        # self.pw.setXRange(-10, 0)

        self.curve_data_max_len = 2500


        self.data = np.empty(shape=(0,curves_eeg_num+1))

        with open(config_file, 'r') as file:
            self.usr_config_json = json.load(file)

        # print(self.usr_config_json)
        # self.show_ch = np.ones(shape=8)

        # self.show_ch = np.fromstring(self.usr_config_json[cv.JSON_CH_SHOW_KEY_STR])
        self.show_ch = np.array(self.usr_config_json['CH'])

        curves_num = len(self.curves)
        
        # if self.show_ch.size==self.curves_num_constant:
        # for i, s in enumerate(self.show_ch):
        #     if i<curves_num:
        #         if s==1:
        #             self.checkboxes[i].setChecked(True)
        #             self.curves[i].show()
        #         else:
        #             self.checkboxes[i].setChecked(False)
        #             self.curves[i].hide()

        for i, s in enumerate(self.show_ch):
            if i<curves_num:
                if s==1:
                    self.checkboxes[self.ch_list[i]].setChecked(True)
                    self.curves[i].show()
                else:
                    self.checkboxes[self.ch_list[i]].setChecked(False)
                    self.curves[i].hide()

        for name, checkbox in self.checkboxes.items():
            checkbox.stateChanged.connect(self.cb_handler)

        for name, checkbox in self.checkboxes.items():
            checkbox.stateChanged.connect(self.cb_handler)

            # if checkbox.isChecked():  # 如果这个checkbox被选中
            #     print(f"{name} is selected")


        # for i in range(self.curves_num_constant):
        #      self.checkboxes[i].stateChanged.connect(self.cb_handler)

        self.settings = QSettings(ini_file, QSettings.IniFormat)     
        # Initial window size/pos last saved. Use default values for first time
        self.resize(self.settings.value("size", QSize(270, 225)))
        if (self.settings.value("pos") is not None) and (self.settings.value("size") is not None):
            screenRect = QApplication.desktop().screenGeometry()
            self.height = screenRect.height()
            if self.settings.value("pos").x()<(screenRect.width()-100) and \
                self.settings.value("pos").y()<(screenRect.height()-100):
                self.move(self.settings.value("pos", QPoint(50, 50)))            

    def __del__(self):
        dp.dpt('del curvesform')

    def closeEvent(self, e):
        # Write window size and position to config file
        self.settings.setValue("size", self.size())
        self.settings.setValue("pos", self.pos())
        e.accept()
        
    def close_win(self):
        dp.dpt('curveform close')
        self.settings.setValue("size", self.size())
        self.settings.setValue("pos", self.pos())

        self.usr_config_json['CH']=list(self.show_ch)

        with open(config_file, "w") as outfile:
            json.dump(self.usr_config_json, outfile)    

        self.close()


    def cb_handler(self):
        # for i in range(self.curves_num_constant):
        #     if (self.checkboxes[i].isChecked()):
        #         self.curves[i].show()
        #         self.show_ch[i]=1
        #     else:
        #         self.show_ch[i]=0
        #         self.curves[i].hide()

        # self.usr_config_json['CH']=list(self.show_ch)


        for name, checkbox in self.checkboxes.items():
            i = self.ch_list.index(name)

            if checkbox.isChecked():  # 如果这个checkbox被选中
                # print(f"{name} --- {i} is selected")
                self.curves[i].show()
                self.show_ch[i]=1
            else:
                self.curves[i].hide()
                self.show_ch[i]=0









    def deal_with_data_inlet(self,elapsed_time,y):

        # dp.dpt(y.shape)

        # if y.shape[1]==1: 
        #     y = np.hstack((y,np.zeros(shape=(y.shape[0],7))))
        # if use 1 ch, pad the data in other channels with zeros

        t = np.expand_dims(elapsed_time, axis=1)

        d = np.hstack((t,y))

        self.data = np.concatenate((self.data,d), axis=0)

        num_del = self.data.shape[0] - self.curve_data_max_len

        if(num_del>0):
            self.data = np.delete(self.data,np.s_[:num_del], axis=0)

        # dp.dpt(self.data[0, 1])
        # dp.dpt(self.data[0, 2])

        for i in range(self.data.shape[1]-1):
            # if self.show_ch[i]:
            #     # self.curves[i].setData(x=self.data[:,0], y=self.data[:, i+1]+self.scale_offset*i)
            #     # self.curves[i].setData(y=self.data[:, i+1]+self.scale_offset*i)
            #     voltage_value = (self.data[:, i+1])*0.067 # gain=8,ref=4.5v*2,24bit,LSB=0.067uV
            #     # voltage_value = (self.data[:, i+1]-32768)*0.2 # gain=8.48*23.5=199.28,ref=2.5v,16bit,LSB=0.2uV
            #     self.curves[i].setData(x=self.data[:,0],y=voltage_value+self.scale_offset*i)

            voltage_value = (self.data[:, i+1])*0.067 # gain=8,ref=4.5v*2,24bit,LSB=0.067uV
            self.curves[i].setData(x=self.data[:,0],y=voltage_value+self.scale_offset*i)
